package com.ljh.controller;

import com.ljh.domain.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author LongJinHua
 * @date 2022-10-10
 */

@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/list")
    public List<Book> list() {
        return mongoTemplate.findAll(Book.class);
    }

    @PostMapping("/add")
    public void add(@RequestBody Book book) {
        mongoTemplate.insert(book, Book.class.getSimpleName().toLowerCase());
        log.info("新增成功:" + book);
    }

    @PutMapping("/update")
    public void update(@RequestBody Book book) {
        mongoTemplate.save(book, Book.class.getSimpleName().toLowerCase());
        log.info("更新成功：" + book);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable String id) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)), Book.class.getSimpleName().toLowerCase());
        log.info("删除成功：" + id);
    }

    // 根据id查询书籍信息
    @GetMapping("/get/{id}")
    public Book getUserById(@PathVariable String id) {
        return mongoTemplate.findById(id, Book.class);
    }
}
